import re
from flask import Flask, request
from datetime import datetime
from dingtalkchatbot.chatbot import DingtalkChatbot

app = Flask(__name__)
# 设置 Webhook 地址
url = "https://oapi.dingtalk.com/robot/send?access_token=c54fa6837d584b0abc56c0a7d0456ca37d59213dcc7ea3f6f104b20de3c71284"
secret = "SEC9de9f15e7d9bc3be3c0c5f50adcf283ff26189940919486b9cdb0feda9ee45b1"
# 初始化机器人
bot = DingtalkChatbot(webhook=url, secret=secret)

# domain_pattern = r"(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}"
# date_pattern = r"\d{4}-\d{2}-\d{2}\s-\s\d{4}-\d{2}-\d{2}"
# day_pattern = r"\((\d+)\)"

# 使用正则提取行信息
pattern = r"([\w.-]+)\s+(\d{4}-\d{2}-\d{2})\s-\s(\d{4}-\d{2}-\d{2})\s\(剩([\d]+)天\)"


def nowTime():
    now = datetime.now()
    # 将时间格式化为字符串
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_time


@app.route("/SSL_webhook", methods=["POST"])
def ssl_webhook():
    # 处理来自 Webhook 的请求数据
    data = request.get_json()
    lines = re.findall(pattern, data["content"])
    # 提取域名
    # domain = re.search(domain_pattern, data["content"]).group()
    # 提取时间段
    # date = re.search(date_pattern, data["content"]).group()
    # 提取天数
    # number = re.search(day_pattern, data["content"]).group(1)

    # 做相关操作
    nowtime = nowTime()
    # 重新格式化
    formatted_lines = [
        f"{line[0]} {line[1]} - {line[2]} (剩{line[3]}天)" for line in lines
    ]
    # 将格式化结果赋值给变量
    results = formatted_lines
    # msg = "*当前时间：{} \n 以下域名SSL证书即将到期: \n {} \n 敬请关注！*".format(nowtime, results)
    # 将 print 的拼接内容作为消息发送给钉钉
    msg = (
        "#### SSL 证书到期提醒 \n"
        + "##### 当前时间："
        + nowtime
        + "\n##### 详细信息：\n###### "
        + " \n###### ".join(results)
    )
    print(msg)
    bot.send_markdown(
        title="SSL证书到期提醒",
        text=msg,
        is_at_all=False,
    )

    # 在这里添加您希望执行的逻辑，处理 Webhook 数据
    return "success"


@app.route("/Domain_webhook", methods=["POST"])
def domain_webhook():
    # 处理来自 Webhook 的请求数据
    data = request.get_json()
    lines = re.findall(pattern, data["content"])
    # 提取域名
    # domain = re.search(domain_pattern, data["content"]).group()
    # 提取时间段
    # date = re.search(date_pattern, data["content"]).group()
    # 提取天数
    # number = re.search(day_pattern, data["content"]).group(1)

    # 做相关操作
    nowtime = nowTime()
    # 重新格式化
    formatted_lines = [
        f"{line[0]} {line[1]} - {line[2]} (剩{line[3]}天)" for line in lines
    ]
    # 将格式化结果赋值给变量
    results = formatted_lines
    # msg = "*当前时间：{} \n 以下域名SSL证书即将到期: \n {} \n 敬请关注！*".format(nowtime, results)
    # 将 print 的拼接内容作为消息发送给钉钉
    msg = (
        "#### 域名到期提醒 \n"
        + "##### 当前时间："
        + nowtime
        + "\n##### 详细信息：\n###### "
        + " \n###### ".join(results)
    )
    print(msg)
    bot.send_markdown(
        title="域名到期提醒",
        text=msg,
        is_at_all=False,
    )

    # 在这里添加您希望执行的逻辑，处理 Webhook 数据
    return "success"


if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)
